package com.appspot.battlerafts.servlets.lobby;

import com.appspot.battlerafts.classes.Game;
import com.appspot.battlerafts.enums.GameState;
import com.appspot.battlerafts.jsons.WaitingGamesJSON;
import com.appspot.battlerafts.utils.PMF;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: Tonis
 * Date: 02.04.12
 * Time: 11:47
 * To change this template use File | Settings | File Templates.
 */
public class GetWaitingGames extends HttpServlet {
    private static final Logger log = Logger.getLogger(GetWaitingGames.class.getName());
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query q = pm.newQuery(Game.class);
        q.setFilter("gameState == '" + GameState.WAITING.toString() + "' && gamePrivate == false");
//        q.setFilter("gamePrivate == false");
        List<Game> waitingGames = (List<Game>) q.execute();
        log.info(waitingGames.toString());
        log.setLevel(Level.INFO);
//        waitingGames.get(0).getItendedPlayers();
        WaitingGamesJSON waitingGamesJSON = new WaitingGamesJSON();
        waitingGamesJSON.waitingGames = waitingGames;

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();

        writer.write(gson.toJson(waitingGamesJSON));
    }
}
